package com.foreknow.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreknow.entity.Department;
import com.foreknow.entity.Rule;
import com.foreknow.entity.Scheduling;
import com.foreknow.entity.User;
import com.foreknow.service.SchedulingService;
import com.foreknow.utils.Constance;
import com.foreknow.utils.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/doctor")
public class SchedulingController {
    @Autowired
    private SchedulingService schedulingService;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");

    /**
     * 分页查询
     *
     * @param para
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping(value = "/doctorduty", method = RequestMethod.GET)
    @ResponseBody
    public String doctorduty(@RequestParam Map<String, Object> para) throws JsonProcessingException {
        int page = Integer.parseInt((String) para.get("pagenum"));
        int size = Integer.parseInt((String) para.get("pagesize"));
        String value = (String) para.get("value1");
        //设置分页信息(当前的页码和每页的数据数量)
        PageHelper.startPage(page, size);
        List<Scheduling> list = new ArrayList<>();
        HashMap<String, Object> hs = new HashMap<>();
        if (value.equals("") || value.equals("null")) {
            list = schedulingService.All((String) para.get("query"));
        } else {
            list = schedulingService.getSomeByDate((String) para.get("value1"), (String) para.get("value2"));

        }
        PageInfo<Scheduling> pageInfo = new PageInfo(list);
        hs.put("data", pageInfo.getList());
        hs.put("total", pageInfo.getTotal());
        hs.put("meta", new Constance("msg", 200));
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    /**
     * 查询所有科室
     *
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping(value = "/departments", method = RequestMethod.GET)
    @ResponseBody
    public String findAllDepartment() throws JsonProcessingException {
        List<Department> deptlist = schedulingService.getAllDepart();
        HashMap<String, Object> hs = new HashMap<>();
        hs.put("data", deptlist);
        hs.put("meta", new Constance("msg", 200));
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    /**
     * 根据科室以及挂号等级查询医生
     *
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping(value = "/addrules", method = RequestMethod.POST)
    @ResponseBody
    public String findUserByDeptAndLevel(@RequestBody Map<String, Object> para) throws JsonProcessingException {
        String d = (String) para.get("isok");
        String l = (String) para.get("isook");
        HashMap<String, Object> hs = new HashMap<>();
        List<User> userList = schedulingService.getUser(d, l);
        hs.put("data", userList);
        hs.put("token", userList.size());
        hs.put("meta", new Constance("msg", 200));
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }

    /**
     * 添加值班规则
     *
     * @param para
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping(value = "/addrulebyrealname", method = RequestMethod.POST)
    @ResponseBody
    public String addRuleByRealname(@RequestBody Map<String, Object> para) throws JsonProcessingException {
        String name = (String) para.get("rlname");
        String rulename = (String) para.get("inputkey");

//        获取到userid，deptid，以及delmark
        User user = schedulingService.getUserIdByName(name);
        String[] w = new String[14];
        w[0] = (String) para.get("week1");
        w[1] = (String) para.get("week2");
        w[2] = (String) para.get("week3");
        w[3] = (String) para.get("week4");
        w[4] = (String) para.get("week5");
        w[5] = (String) para.get("week6");
        w[6] = (String) para.get("week7");
        w[7] = (String) para.get("week8");
        w[8] = (String) para.get("week9");
        w[9] = (String) para.get("week10");
        w[10] = (String) para.get("week11");
        w[11] = (String) para.get("week12");
        w[12] = (String) para.get("week13");
        w[13] = (String) para.get("week14");
        for (int i = 0; i < 14; i++) {
            if (w[i] == null) {
                w[i] = "0";
            }
        }
        String week = w[0] + w[1] + w[2] + w[3] + w[4] + w[5] + w[6] + w[7] + w[8] + w[9] + w[10] + w[11] + w[12] + w[13];
        Rule rule = new Rule();
        rule.setRulename(rulename);
        rule.setDeptid(user.getDeptid());
        rule.setUserid(user.getId());
        rule.setWeek(week);
        rule.setDelmark(user.getDelmark());

        int iok = schedulingService.addRule(rule);

        HashMap<String, Object> hs = new HashMap<>();
        hs.put("data", iok);
//        hs.put("token",userList.size());
        hs.put("meta", new Constance("msg", 201));
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }


    @RequestMapping(value = "/generateplan", method = RequestMethod.POST)
    @ResponseBody
    public String generatePlan(@RequestBody Object[] para) throws JsonProcessingException, ParseException {
        //用来储存开始日期和结束日期
        List<Object> timelist = new ArrayList<>();
        User user = new User();
        List<Object> userlist = new ArrayList<>();
        //创建一个用来接收week拆分之后的数组
        char[] weekarray = new char[14];
        //用来接收需要值班的日期
//                        List<String> newdateList=new ArrayList<>();
        //最后传到service层的集合
        List<Scheduling> schedulingslist = new ArrayList<>();
        //用来接收上午下午的字符串集合
//                          List<String> noonlist=new ArrayList<>();

        //把开始日期和结束日期与用户分开
        for (int i = 0; i < para.length; i++) {
            if (para[i] instanceof String) {
                timelist.add(para[i]);
            } else {
                //     user=(User)para[i];不要这么整！！！！！！！
                userlist.add(para[i]);
            }
        }
        //获取开始日期和结束日期，用来生成中间的所有日期
        String startTime = (String) timelist.get(0);
        String endTime = (String) timelist.get(1);
        //                 获取两个日期之间的所有日期(包含开始时间和结束时间)
        List<String> dateList = schedulingService.getTimesBetweenDates(startTime, endTime);

        //获取到week，用来判断当日的上下午是否值班
        for (int i = 0; i < userlist.size(); i++) {
            //获取并拆分week字符串
            String string = userlist.get(i).toString();
            //查找到"week"所在的位置
            int isright = string.indexOf("week");
            weekarray = string.substring(isright + 5, isright + 19).toCharArray();
            //挑选出需要值班的日期
            //每间隔14天再循环
            int h = 0;
            int j = 0;
            for (; j < weekarray.length; j++) {

                if (weekarray[j] == '1' && (j + 1) % 2 != 0) {
                    //获取最终的Scheduling对象，用来添加到Scheduling表中
                    Scheduling scheduling = new Scheduling();
//                                  newdateList.add(dateList.get(h));
                    //String转date
//                                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
//                                  Date date = simpleDateFormat.parse(dateList.get(h));
                    scheduling.setScheddate(dateList.get(h));
                    scheduling.setNoon("上午");

                    schedulingslist.add(scheduling);
//                                  noonlist.add("上午");
                }
                if (weekarray[j] == '1' && j % 2 != 0) {
                    //获取最终的Scheduling对象，用来添加到Scheduling表中
                    Scheduling scheduling = new Scheduling();
//                                  newdateList.add(dateList.get(h));

                    //String转date
//                                      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
//                                      Date date = simpleDateFormat.parse(dateList.get(h));
                    scheduling.setScheddate(dateList.get(h));
                    scheduling.setNoon("下午");

                    schedulingslist.add(scheduling);
                    h++;
//                                  noonlist.add("下午");
                }
                if (weekarray[j] == '0' && j % 2 != 0) {
                    h++;
                }
            }
        }


        //最后，把所有的对象赋值（赋需要的值）
        for (int i = 0; i < schedulingslist.size(); i++) {
            int u = 0;
            //将集合中的对象变成字符串，再截取需要的信息
            String schString = userlist.get(u).toString();
            //获取用户id
            //截取子字符串
            String str = schString.substring(1, 9);
            //获得到子字符串中的数字（id）
            str = str.trim();
            String str2 = "";
            if (str != null && !"".equals(str)) {
                for (int j = 0; j < str.length(); j++) {
                    if (str.charAt(j) >= 48 && str.charAt(j) <= 57) {
                        str2 += str.charAt(j);
                    }
                }
            }
            int id = Integer.parseInt(str2);
            //获取部门id
            //查找到"deptid"所在的位置
            int deptidaddress = schString.indexOf("deptid");
            //截取子字符串
            String deptid = schString.substring(deptidaddress, deptidaddress + 9);
            //获得到子字符串中的数字（id）
            deptid = deptid.trim();
            String deptid2 = "";
            if (deptid != null && !"".equals(deptid)) {
                for (int j = 0; j < deptid.length(); j++) {
                    if (deptid.charAt(j) >= 48 && deptid.charAt(j) <= 57) {
                        deptid2 += deptid.charAt(j);
                    }
                }
            }
            //获取Delmark
            //查找到"delmark"所在的位置
            int delmarkaddress = schString.indexOf("delmark");
            //截取子字符串
            String delmark = schString.substring(delmarkaddress, delmarkaddress + 9);
            //获得到子字符串中的数字（id）
            delmark = delmark.trim();
            String delmark2 = "";
            if (delmark != null && !"".equals(delmark)) {
                for (int j = 0; j < delmark.length(); j++) {
                    if (delmark.charAt(j) >= 48 && delmark.charAt(j) <= 57) {
                        delmark2 += delmark.charAt(j);
                    }

                }
                //获取Week
                //查找到"week"所在的位置
                int weekaddress = schString.indexOf("week");

                //截取子字符串
                String week = schString.substring(weekaddress + 5, weekaddress + 19);
                //调用查找RuleId的方法，赋值给schedulings对象
//                                    int ruleid=schedulingService.getRuleId(week,id);

                // 找到schedulingslist集合中的对象，对其赋值
                Scheduling schedulings = schedulingslist.get(i);
                schedulings.setDeptid(Integer.parseInt(deptid2));
                schedulings.setUserid(id);
                schedulings.setDelmark(Integer.parseInt(delmark2));
//                                   schedulings.setRuleid(ruleid);
            }


        }
        int iok = schedulingService.addscheduling(schedulingslist);
        HashMap<String, Object> hs = new HashMap<>();
        hs.put("data", iok);
        //        hs.put("token",schedulingslist.size());
        hs.put("meta", new Constance("msg", 201));
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(hs);
    }
}